'use strict';

const Service = require('egg').Service;


class BorrowService extends Service {
    async page(query) {
        const { ctx, app } = this
        const { Op } = app.Sequelize
        const { page, limit } = query
        const where = { upt_act: { [Op.ne]: 'D' } };

        const { username } = ctx.state.user
        const { userid } = ctx.state.user;
        const user = await ctx.model.Sys.User.findOne({
            include: {
                model: ctx.model.Sys.Role,
                attributes: ['name']
            },
            where: { id: userid },
            attributes: ['id', 'username']
        });
        const name = user.dataValues.sys_roles[0].dataValues.name
        if (name != '超级管理员') {
            where.username = username
        }
        if (query.book_num) {
            where.book_num = { [Op.like]: `%${query.book_num}%` };
        }
        if (query.username) {
            where.username = { [Op.like]: `%${query.username}%` };
        }
        if (query.state) {
            if (query.state == '已归还') {
                where.state = '1'
            } else {
                where.state = '0'
            }
        }
        let lendtime = ctx.helper.formatTime(query.lend_time).split(' ')[0]
        if(query.lend_time) {
            where.lend_time = app.Sequelize.where(app.Sequelize.fn('date', app.Sequelize.col('lend_time')), lendtime)
        }
        let reverttime = ctx.helper.formatTime(query.revert_time).split(' ')[0]
        if(query.revert_time) {
            where.revert_time = app.Sequelize.where(app.Sequelize.fn('date', app.Sequelize.col('revert_time')), reverttime)
        }

        let Bookwhere = {}
        if (query.book_name) {
            Bookwhere.book_name = { [Op.like]: `%${query.book_name}%` };
        }
        if (query.writer) {
            Bookwhere.writer = { [Op.like]: `%${query.writer}%` };
        }
        if (query.site) {
            Bookwhere.site = query.site
        }

        return await ctx.model.Borrow.findAndCountAll({
            where,
            include: {
                model: ctx.model.Book,
                attributes: ['book_name', 'writer', 'site', 'amount'],
                where: Bookwhere,
            },
            offset: (page - 1) * limit,
            limit: parseInt(limit),
            order: [['created_at', 'desc']],
        })
    }
    async borrowBook(body) {
        const { ctx } = this
        //获取token时候需要在接口上面加上jwt，不然没有token获取不到state里面的user
        const { username } = ctx.state.user
        body.username = username
        body.lend_time = ctx.helper.formatTime(new Date());

        const res = await ctx.model.Borrow.findAll({
            where: {
                username: username,
                book_num: body.book_num,
                state: '0'
            }
        })
        if (res[0]) {
            return { msg: `这本${body.book_name}您已经借阅了！` }
        }

        let data = new Date()
        let m = data.getMonth() + 1
        let arr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        let curMonthDays = arr[m - 1]
        let time = body.lend_time.split(' ')

        body.revert_time = this.help(curMonthDays, body) + ' ' + time[1]
        // console.log(body.revert_time);
        //初始化实际归还时间等于理论归还时间
        // body.real_time = body.revert_time

        try {
            return await ctx.model.Borrow.create(body) &&
                (await ctx.model.Book.update({ amount: body.amount - 1 }, { where: { book_num: body.book_num } }))[0]
        } catch (error) {
            console.log(error);
            return false
        }
    }
    help(monthDays, body) {
        let data = new Date()
        //当前日期（天）
        let d = data.getDate()
        //当前月份 0-11
        let m = data.getMonth() + 1
        //当前年份
        let y = data.getFullYear()
        let curY, curM, curD
        //如果是2月并且是闰年，则加1
        if ((monthDays == 28) && (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0))) {
            monthDays = monthDays + 1
        }
        //2月份特殊情况判断，这里只做隔月计算，因为需求最多只有30天，大于30这里没有做判断
        if (m == 1) {
            let nextMonthDays
            if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {
                nextMonthDays = 29
            } else {
                nextMonthDays = 28
            }
            if (d + body.borrow_time - nextMonthDays - monthDays > 0) {
                curD = d + body.borrow_time - nextMonthDays - monthDays
                curM = m + 2
                curY = y
                return (curD >= 10 ? `${curY}-0${curM}-${curD}` : `${curY}-0${curM}-0${curD}`)
            }
        }
        if ((d + body.borrow_time) > monthDays) {
            curD = d + body.borrow_time - monthDays
            curM = m + 1
            if (curM > 12) {
                curY = y + 1
                curM = curM - 12
            } else {
                curY = y
            }
        } else {
            curY = y
            curM = m
            curD = d + body.borrow_time
        }
        return curM >= 10 ?
            (curD >= 10 ? `${curY}-${curM}-${curD}` : `${curY}-${curM}-0${curD}`)
            :
            (curD >= 10 ? `${curY}-0${curM}-${curD}` : `${curY}-0${curM}-0${curD}`)
    }
    async revertBook(body) {
        const { ctx,app } = this
        const { Op } = app.Sequelize
        // console.log(body);
        const { username } = ctx.state.user
        let data = {}
        data.upt_act = 'U'
        data.state = '1'
        data.updated_at = ctx.helper.formatTime(new Date())
        data.real_time = ctx.helper.formatTime(new Date())
        try {
            await ctx.model.Message.update({ upt_act: 'D',updated_at: ctx.helper.formatTime(new Date())}, { where: { username: username, book_num: body.book_num, upt_act: { [Op.ne]: 'D' } } })
            return (await ctx.model.Borrow.update(data, { where: { username: body.username, book_num: body.book_num } }))[0] &&
                (await ctx.model.Book.update({ amount: body.book.amount + 1 }, { where: { book_num: body.book_num } }))[0]
        } catch (error) {
            console.log(error);
            return false
        }
    }
}
module.exports = BorrowService;